package com.ruoyi.system.service.impl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;

import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.AdminConfig;
import cn.wildfirechat.sdk.MessageAdmin;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.ruoyi.system.domain.SendHistory;
import com.ruoyi.system.domain.TGroup;
import com.ruoyi.system.dto.GroupSendMessage;
import com.ruoyi.system.imDomain.TextMessageContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.ruoyi.system.mapper.TMessagesMapper;
import com.ruoyi.system.mapper.TUserMessagesMapper;
import com.ruoyi.system.domain.TMessages;
import com.ruoyi.system.domain.TUserMessages;
import com.ruoyi.system.service.ITMessagesService;
import com.ruoyi.system.utils.ShardingTableUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 消息】Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-18
 */
@Service
@Slf4j
public class TMessagesServiceImpl implements ITMessagesService 
{
    @Autowired
    private TMessagesMapper tMessagesMapper;
    
    @Autowired
    private TUserMessagesMapper tUserMessagesMapper;
    @Value("${admin:admin}")
    private String admin;

    /**
     * 查询消息】
     * 
     * @param id 消息】主键
     * @return 消息】
     */
    @Override
    public TMessages selectTMessagesById(Long id)
    {
        return tMessagesMapper.selectTMessagesById(id);
    }

    /**
     * 查询消息列表
     * 可以查询指定用户的消息，也可以查询所有用户的消息
     * 
     * @param tMessages 消息
     * @return 消息
     */
    @Override
    public TableDataInfo selectTMessagesList(TMessages tMessages, int pageNum, int pageSize)
    {
        List<TMessages> resultList = new ArrayList<>();
        long totalCount = 0;
        
        // 如果指定了用户ID，进行分表查询用户相关消息
        if (StringUtils.hasText(tMessages.getQueryUserId())) {
            // 计算用户消息表名（MySQL环境）
            String userMessagesTableName = ShardingTableUtils.getUserMessagesTableName(tMessages.getQueryUserId(), false);
             
             // 查询用户消息记录
             List<TUserMessages> userMessagesList = tUserMessagesMapper.selectTUserMessagesByUserId(tMessages.getQueryUserId(), userMessagesTableName);
             totalCount = userMessagesList.size();
             
             // 手动分页用户消息记录
             int startIndex = (pageNum - 1) * pageSize;
             int endIndex = Math.min(startIndex + pageSize, userMessagesList.size());
             
             if (startIndex < userMessagesList.size()) {
                 List<TUserMessages> pagedUserMessages = userMessagesList.subList(startIndex, endIndex);
                 
                 // 根据分页后的用户消息记录查询具体消息
                 for (TUserMessages userMessage : pagedUserMessages) {
                     // 计算消息表名（根据消息时间，MySQL环境）
                     String messagesTableName = ShardingTableUtils.getMessagesTableName(userMessage.getDt(), false);
                     
                     // 查询具体消息
                     TMessages message = tMessagesMapper.selectTMessagesById(Long.valueOf(userMessage.getMid()), messagesTableName);
                     
                     if (message != null) {
                         resultList.add(message);
                     }
                 }
             }
        } else {
            // 没有指定用户ID，查询所有36张消息表获取所有消息（包括用户消息和群组消息）
            List<TMessages> allMessages = new ArrayList<>();
            
            for (int i = 0; i < 36; i++) {
                String tableName = "t_messages_" + i;
                try {
                    List<TMessages> tableMessages = tMessagesMapper.selectTMessagesList(tMessages, tableName);
                    if (tableMessages != null && !tableMessages.isEmpty()) {
                        allMessages.addAll(tableMessages);
                    }
                } catch (Exception e) {
                    // 跳过不存在的表
                    log.warn("查询表 {} 时出现异常，跳过该表: {}", tableName, e.getMessage());
                }
            }
            
            // 按时间倒序排序
            allMessages.sort((a, b) -> {
                if (a.getDt() == null && b.getDt() == null) return 0;
                if (a.getDt() == null) return 1;
                if (b.getDt() == null) return -1;
                return b.getDt().compareTo(a.getDt());
            });
            
            totalCount = allMessages.size();
            
            // 手动实现分页
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, allMessages.size());
            
            if (startIndex < allMessages.size()) {
                resultList = allMessages.subList(startIndex, endIndex);
            }
        }
        for (TMessages messages : resultList) {
            // 获取用户信息
            enrichMessageWithUserInfo(messages);
        }

        // 构造分页结果
        TableDataInfo dataTable = new TableDataInfo();
        dataTable.setRows(resultList);
        dataTable.setTotal(totalCount);
        dataTable.setCode(200);
        dataTable.setMsg("查询成功");
        
        return dataTable;
    }
    
    /**
     * 分页查询消息列表（支持分表分页）
     * 可以查询指定用户的消息，也可以查询所有用户的消息
     * 
     * @param tMessages 查询条件
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Override
    public TableDataInfo selectTMessagesListWithPaging(TMessages tMessages, int pageNum, int pageSize)
    {
        TableDataInfo dataTable = new TableDataInfo();
        List<TMessages> resultList = new ArrayList<>();
        long totalCount = 0;
        
        // 如果指定了用户ID，进行分表查询
        if (StringUtils.hasText(tMessages.getQueryUserId())) {
            // 计算用户消息表名（MySQL环境）
            String userMessagesTableName = ShardingTableUtils.getUserMessagesTableName(tMessages.getQueryUserId(), false);
             
            // 使用PageHelper进行分页查询用户消息记录
            PageHelper.startPage(pageNum, pageSize);
            List<TUserMessages> userMessagesList = tUserMessagesMapper.selectTUserMessagesByUserId(tMessages.getQueryUserId(), userMessagesTableName);
            PageInfo<TUserMessages> pageInfo = new PageInfo<>(userMessagesList);
            
            totalCount = pageInfo.getTotal();
             
            // 根据用户消息记录查询具体消息
            for (TUserMessages userMessage : userMessagesList) {
                // 计算消息表名（根据消息时间，MySQL环境）
                String messagesTableName = ShardingTableUtils.getMessagesTableName(userMessage.getDt(), false);
                 
                // 查询具体消息
                TMessages message = tMessagesMapper.selectTMessagesById(Long.valueOf(userMessage.getMid()), messagesTableName);
                 
                if (message != null) {
                    resultList.add(message);
                }
            }
        } else {
            // 没有指定用户ID时，查询所有36张消息表（t_messages_0到t_messages_35）
            // 为了性能考虑，采用分批查询策略
            List<TMessages> allMessages = new ArrayList<>();
            
            // 查询所有36张消息表
            for (int i = 0; i < 36; i++) {
                String tableName = "t_messages_" + i;
                try {
                    List<TMessages> tableMessages = tMessagesMapper.selectTMessagesList(tMessages, tableName);
                    if (tableMessages != null && !tableMessages.isEmpty()) {
                        allMessages.addAll(tableMessages);
                    }
                } catch (Exception e) {
                    // 如果表不存在，跳过
                    log.warn("查询表 {} 失败: {}", tableName, e.getMessage());
                }
            }
            
            // 按时间倒序排序
            allMessages.sort((a, b) -> {
                if (a.getDt() == null && b.getDt() == null) return 0;
                if (a.getDt() == null) return 1;
                if (b.getDt() == null) return -1;
                return b.getDt().compareTo(a.getDt());
            });
            
            // 手动分页
            totalCount = allMessages.size();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, allMessages.size());
            
            if (startIndex < allMessages.size()) {
                resultList = allMessages.subList(startIndex, endIndex);
            }
        }
        for (TMessages messages : resultList) {
            // 获取用户信息
            enrichMessageWithUserInfo(messages);
        }

        dataTable.setCode(200);
        dataTable.setMsg("查询成功");
        dataTable.setRows(resultList);
        dataTable.setTotal(totalCount);
        
        return dataTable;
    }

    private void enrichMessageWithUserInfo(TMessages message) {
        if (message == null) return;
        try {
            IMResult<InputOutputUserInfo> fromUserResult = UserAdmin.getUserByUserId(message.getFrom());
            if (fromUserResult != null && fromUserResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
                message.setFrom(fromUserResult.getResult().getDisplayName());
            }
            IMResult<InputOutputUserInfo> toUserResult = UserAdmin.getUserByUserId(message.getTarget());
            if (toUserResult != null && toUserResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
                message.setTarget(toUserResult.getResult().getDisplayName());
            }
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage());
        }
    }
    /**
     * 新增消息】
     * 
     * @param tMessages 消息】
     * @return 结果
     */
    @Override
    public int insertTMessages(TMessages tMessages)
    {
        return tMessagesMapper.insertTMessages(tMessages);
    }

    /**
     * 修改消息】
     * 
     * @param tMessages 消息】
     * @return 结果
     */
    @Override
    public int updateTMessages(TMessages tMessages)
    {
        return tMessagesMapper.updateTMessages(tMessages);
    }

    /**
     * 批量删除消息
     * 
     * @param ids 需要删除的消息】主键
     * @return 结果
     */
    @Override
    public int deleteTMessagesByIds(Long[] ids)
    {
        for (Long id : ids) {
            try {
                MessageAdmin.deleteMessage(id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return 1;
    }

    @Override
    public Boolean broadcastMessage(String text) {
        TextMessageContent textMessageContent = new TextMessageContent(text);
        MessagePayload payload = textMessageContent.encode();
        try {
            IMResult<BroadMessageResult> resultBroadcastMessage = MessageAdmin.broadcastMessage(admin, 0, payload);
            if (resultBroadcastMessage != null && resultBroadcastMessage.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
                log.info("broad message success, send message to " + resultBroadcastMessage.getResult().getCount() + " users");
                // 保存群发文本数据
                SendHistory sendHistory = new SendHistory();
                sendHistory.setTargetType(ProtoConstants.ConversationType.ConversationType_Private);
                sendHistory.setSenderId(admin);
                sendHistory.setContent(text);
                sendHistory.setSendTime(LocalDateTime.now());
                sendHistory.setStatus(1);
                sendHistory.setMsgUid(resultBroadcastMessage.getResult().getMessageUid());
                sendHistory.setCreatedAt(LocalDateTime.now());
                sendHistory.setCategory(1);
                tMessagesMapper.insertSendMessage(sendHistory);
            } else {
                log.info("broad message failure");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public Boolean groupMessage( GroupSendMessage message) {
        for (String id : message.getIds()) {
            String sender = admin;
            Conversation conversation = new Conversation();
            conversation.setTarget(id);
            conversation.setType(ProtoConstants.ConversationType.ConversationType_Group);
            //测试发送文本消息
            TextMessageContent textMessageContent = new TextMessageContent(message.getText());
            //消息转成Payload并发送
            MessagePayload payload = textMessageContent.encode();
            try {
                IMResult<SendMessageResult> resultSendMessage = MessageAdmin.sendMessage(sender, conversation, payload, null);
                if (resultSendMessage != null && resultSendMessage.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
                    // 保存群发文本数据
                    SendHistory sendHistory = new SendHistory();
                    sendHistory.setTarget(id);
                    sendHistory.setTargetType(ProtoConstants.ConversationType.ConversationType_Group);
                    sendHistory.setSenderId(sender);
                    sendHistory.setContent(message.getText());
                    sendHistory.setSendTime(LocalDateTime.now());
                    sendHistory.setStatus(1);
                    sendHistory.setMsgUid(resultSendMessage.getResult().getMessageUid());
                    sendHistory.setCreatedAt(LocalDateTime.now());
                    sendHistory.setCategory(2);
                    tMessagesMapper.insertSendMessage(sendHistory);
                    log.info("send message success");
                } else {
                    log.info("send message failure");

                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }

    @Override
    public List<SendHistory> sendGroupMessageList() {
        return tMessagesMapper.getSendGroupMessageList(2);
    }

    @Override
    public List<TMessages> exportTMessagesList(TMessages tMessages) {
        List<TMessages> resultList = new ArrayList<>();
        // 计算用户消息表名（MySQL环境）
        String userMessagesTableName = ShardingTableUtils.getUserMessagesTableName(tMessages.getQueryUserId(), false);
        // 查询用户消息记录
        List<TUserMessages> userMessagesList = tUserMessagesMapper.selectTUserMessagesByUserId(tMessages.getQueryUserId(), userMessagesTableName);

        // 根据用户消息记录查询具体消息
        for (TUserMessages userMessage : userMessagesList) {
            // 计算消息表名（根据消息时间，MySQL环境）
            String messagesTableName = ShardingTableUtils.getMessagesTableName(new Date(),false);
            // 查询具体消息
            TMessages message = tMessagesMapper.selectTMessagesById(Long.valueOf(userMessage.getMid()), messagesTableName);
            if (message != null) {
                resultList.add(message);
            }
        }
        for (TMessages messages : resultList) {
            // 获取用户信息
            enrichMessageWithUserInfo(messages);
        }
        return resultList;
    }

    @Override
    public List<SendHistory> broadcastMessageList() {
        return tMessagesMapper.getSendGroupMessageList(1);
    }
}
